package com.lgCore.client.workHandler.impl;

import com.alibaba.fastjson.JSON;
import com.lgCore.client.workHandler.ClientNettyBootStrapPool;
import com.lgCore.client.workHandler.ClientResultQueue;
import com.lgCore.client.workHandler.ICommonRpcClientService;
import com.lgCore.common.RpcBaseCommonEntity;
import com.lgCore.common.RpcException;
import com.lgCore.consumer.model.ClientZkData;
import com.lgCore.factory.RpcServiceZkFactory;
import com.lgCore.netty.client.NettyClientBootstrap;
import com.lgCore.netty.client.handler.NettyClientHandler;
import com.lgCore.netty.message.AskMsg;
import com.lgCore.netty.message.Constants;
import com.lgCore.netty.message.ReplyServerBody;
import io.netty.util.Attribute;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class CommonRpcClientServiceImpl implements ICommonRpcClientService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonRpcClientServiceImpl.class);

    @Override
    public Object executeSendRequest(NettyClientBootstrap clientBootstrap, AskMsg askMsg) throws Exception {

        //记录到队列
        LinkedBlockingQueue<Object> responseQueue = new LinkedBlockingQueue<Object>(1);
//        try {
        ClientResultQueue.putResponse(askMsg.getBusinessId(), responseQueue);
        //发送消息

        Attribute<Constants> constantsAttributeKey = clientBootstrap.getSocketChannel().attr(ClientNettyBootStrapPool.auth);
        Constants constants = constantsAttributeKey.get();
        if (constants != null) {
            askMsg.setClientId(constants.getClientId());
        }
//        LOGGER.info("invok askMsg is"+ JSON.toJSONString(askMsg));
        clientBootstrap.getSocketChannel().writeAndFlush(askMsg);
        //查询队列结果
        Object result = responseQueue.poll(
                RpcBaseCommonEntity.maxMQTime,
                TimeUnit.SECONDS);
        ReplyServerBody replyServerBody = (ReplyServerBody) result;
        if(replyServerBody==null || replyServerBody.getIsSucess()!=1){
            throw new RpcException("rpc 调用接口报错");
        }
        ClientResultQueue.removeResponse(askMsg.getBusinessId());
        return replyServerBody.getData();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public NettyClientBootstrap getServerBootStrap(String serverAddr) {
        NettyClientBootstrap nettyClientBootstrap = ClientNettyBootStrapPool.getChannelByIpAddr(serverAddr);
        return nettyClientBootstrap;
    }

    public String getServerDataByZk(String serverName) {
        return ClientZkData.getValueByPath(serverName);
    }

    public void removeServerBootStrap(String serverAddr) {
        ClientNettyBootStrapPool.delKey(serverAddr);
    }
}
